<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017-09-10
 * Time: 14:31
 */

namespace Qwadmin\Controller;


class ProxyDomainController extends ComController
{

    public function add()
    {
        $this->display('form');
    }
	
	public function x_add()
    {
        $this->display('x_form');
    }

    public function add_bak()
    {
        $this->display('form_bak');
    }
	
	 public function x_add_bak()
    {
        $this->display('x_form_bak');
    }

    public function index($sid = 0, $p = 1)
    {
        $p = intval($p) > 0 ? $p : 1;

        $branch = M('proxy_domain');
        $pagesize = 20;#每页数量
        $offset = $pagesize * ($p - 1);//计算记录偏移量
        $prefix = C('DB_PREFIX');
        $keyword = isset($_GET['keyword']) ? ($_GET['keyword']) : '';

        $where = 'status = 0';

        //$list = D('proxy_domain')->where("domain like '%$keyword%'")->select();

        if ($keyword) {
            $keyword = trim($keyword);
            $where .= " and domain like '%{$keyword}%' ";
        }
        $count = $branch->where($where)->count();
        $list = $branch->where($where)->limit($offset . ',' . $pagesize)->select();
        $page = new \Think\Page($count, $pagesize);
        $page = $page->show();
        $this->assign('list', $list);
        $this->assign('page', $page);
        $this->assign('count',$count);
        $this->display();
    }
	
	
	  public function x_index($sid = 0, $p = 1)
    {
        $p = intval($p) > 0 ? $p : 1;

        $branch = M('x_proxy_domain');
        $pagesize = 20;#每页数量
        $offset = $pagesize * ($p - 1);//计算记录偏移量
        $prefix = C('DB_PREFIX');
        $keyword = isset($_GET['keyword']) ? ($_GET['keyword']) : '';

        $where = 'status = 0';

        //$list = D('proxy_domain')->where("domain like '%$keyword%'")->select();

        if ($keyword) {
            $keyword = trim($keyword);
            $where .= " and domain like '%{$keyword}%' ";
        }
        $count = $branch->where($where)->count();
        $list = $branch->where($where)->limit($offset . ',' . $pagesize)->select();
        $page = new \Think\Page($count, $pagesize);
        $page = $page->show();
        $this->assign('list', $list);
        $this->assign('page', $page);
        $this->assign('count',$count);
        $this->display();
    }

    public function index_bak($sid = 0, $p = 1)
    {
        $p = intval($p) > 0 ? $p : 1;

        $branch = M('proxy_domain_bak');
        $pagesize = 20;#每页数量
        $offset = $pagesize * ($p - 1);//计算记录偏移量
        //$prefix = C('DB_PREFIX');
        $keyword = isset($_GET['keyword']) ? ($_GET['keyword']) : '';
        //$list = D('proxy_domain_bak')->where("domain like '%$keyword%'")->select();
        if ($keyword) {
            $keyword = trim($keyword);
            $where = "domain like '%{$keyword}%' ";
        }
        $count = $branch->where($where)->count();
        $list = $branch->where($where)->limit($offset . ',' . $pagesize)->select();
        $page = new \Think\Page($count, $pagesize);
        $page = $page->show();
        $this->assign('list', $list);
        $this->assign('page', $page);
        $this->assign('count',$count);
        $this->display();
    }
	
	
	  public function x_index_bak($sid = 0, $p = 1)
    {
        $p = intval($p) > 0 ? $p : 1;

        $branch = M('x_proxy_domain_bak');
        $pagesize = 20;#每页数量
        $offset = $pagesize * ($p - 1);//计算记录偏移量
        //$prefix = C('DB_PREFIX');
        $keyword = isset($_GET['keyword']) ? ($_GET['keyword']) : '';
        //$list = D('proxy_domain_bak')->where("domain like '%$keyword%'")->select();
        if ($keyword) {
            $keyword = trim($keyword);
            $where = "domain like '%{$keyword}%' ";
        }
        $count = $branch->where($where)->count();
        $list = $branch->where($where)->limit($offset . ',' . $pagesize)->select();
        $page = new \Think\Page($count, $pagesize);
        $page = $page->show();
        $this->assign('list', $list);
        $this->assign('page', $page);
        $this->assign('count',$count);
        $this->display();
    }

    public function del()
    {

        $ids = isset($_REQUEST['ids']) ? $_REQUEST['ids'] : false;
        if ($ids) {
            if (is_array($ids)) {
                $ids = implode(',', $ids);
                $map['id'] = array('in', $ids);
            } else {
                $map = 'id=' . $ids;
            }
            if (M('proxy_domain')->where($map)->delete()) {
                addlog('删除推广域名，AID：' . $ids);
                $this->success('恭喜，删除成功！');
            } else {
                $this->error('参数错误！');
            }
        } else {
            $this->error('参数错误！');
        }

    }
	
	public function x_del()
    {

        $ids = isset($_REQUEST['ids']) ? $_REQUEST['ids'] : false;
        if ($ids) {
            if (is_array($ids)) {
                $ids = implode(',', $ids);
                $map['id'] = array('in', $ids);
            } else {
                $map = 'id=' . $ids;
            }
            if (M('x_proxy_domain')->where($map)->delete()) {
                addlog('删除推广域名，AID：' . $ids);
                $this->success('恭喜，删除成功！');
            } else {
                $this->error('参数错误！');
            }
        } else {
            $this->error('参数错误！');
        }

    }

    public function update_bak($id = 0){
            $id = intval($id);
            $data['domain'] = isset($_POST['domain'][0]) ? $_POST['domain'][0] : '';
            if (ctype_space($data['domain'])) {
                $this->error('警告！域名必填项目。');
            }
            $domains = $data['domain'];
            $domains = trim($domains);
            $domain_a = explode("\r\n",$domains);
            $domain  = array_filter($domain_a);

            foreach($domain as $v){
                $map['domain'] = trim($v);
                $aid = M('proxy_domain_bak')->data($map)->add();
            }
            $this->success('恭喜！新增成功！');
    }
	
	public function x_update_bak($id = 0){
            $id = intval($id);
            $data['domain'] = isset($_POST['domain'][0]) ? $_POST['domain'][0] : '';
            if (ctype_space($data['domain'])) {
                $this->error('警告！域名必填项目。');
            }
            $domains = $data['domain'];
            $domains = trim($domains);
            $domain_a = explode("\r\n",$domains);
            $domain  = array_filter($domain_a);

            foreach($domain as $v){
                $map['domain'] = trim($v);
                $aid = M('x_proxy_domain_bak')->data($map)->add();
            }
            $this->success('恭喜！新增成功！');
    }

    public function update($id = 0)
    {
        $id = intval($id);
        $data['domain'] = isset($_POST['domain'][0]) ? $_POST['domain'][0] : '';
        $data['status'] = 1;
        if (ctype_space($data['domain'])) {
            $this->error('警告！域名必填项目。');
        }
        $domains = $data['domain'];
        $domains = trim($domains);
        $domain_a = explode("\r\n",$domains);
        $domain  = array_filter($domain_a);

        foreach($domain as $v){
                $map['domain'] = trim($v);
                //$map['domain'] = trim($v);
                $aid = M('proxy_domain')->data($map)->add();
        }
        $this->success('恭喜！新增成功！');
    }
	
	
	 public function x_update($id = 0)
    {
        $id = intval($id);
        $data['domain'] = isset($_POST['domain'][0]) ? $_POST['domain'][0] : '';
        $data['status'] = 1;
        if (ctype_space($data['domain'])) {
            $this->error('警告！域名必填项目。');
        }
        $domains = $data['domain'];
        $domains = trim($domains);
        $domain_a = explode("\r\n",$domains);
        $domain  = array_filter($domain_a);

        foreach($domain as $v){
                $map['domain'] = trim($v);
                //$map['domain'] = trim($v);
                $aid = M('x_proxy_domain')->data($map)->add();
        }
        $this->success('恭喜！新增成功！');
    }

    public function randsendtemplate(){
        $this->display();
    }
	
	
	
	
	public function randsendtemplate1(){	

        if(empty($_POST['link'])){

            $this->error('请您输入链接');

        }

        preg_match_all('/\d+/',$_POST['link'],$arr);
        $order_set = $arr[0][0];
        $novel_id = $arr[0][1];

        $rows = D('user')->select();
        if(!empty($rows)){
            foreach($rows as $key=>$value){
                $aa = D()->query("select domain from qw_proxy_domain where status=0 order by rand() limit 1 ");
                $url = $aa[0]['domain'].'?novel_id='.$novel_id.'&order_set='.$order_set;
               // dump($url);
                $domain = $value['domain'];
                //dump($url);
                //$this->sendtemplateinfo($domain,'推广小说','测试','小说信息','今天',$url,$value['open_id']);
            }
        }
    }
	
	
	
	
	protected function sendtemplateinfo($domain, $title, $remark, $cartoon_info, $update_date, $cartoon_url, $open_id){
        $map["domain"] = $domain;
        //dump($domain);
        $map['is_put'] = 1;
        $platform = D("platform")->where($map)->find();
        $put_template_id = $platform['put_template_id'];
        if(!empty($put_template_id)){
            if(intval($platform["out_time"]) > time())	{
                $token = getWeChatToken($platform["appid"],$platform["secret"],$platform["token"]);
            }
            else{
                $token = getWeChatToken($platform["appid"],$platform["secret"]);
            }

            $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=$token";
            $data = '{
		           "touser":"'.$open_id.'",
		           "template_id":"'.$put_template_id.'",
		           "url":"'.$cartoon_url.'",
		           "data":{
	                   "first": {
	                       "value":"'.$title.'",
	                       "color":"#ff1122"
	                   },
	                   "keyword1":{
	                       "value":"'.$cartoon_info.'",
	                       "color":"#173177"
	                   },
	                   "keyword2": {
	                       "value":"'.$update_date.'",
	                       "color":"#173177"
	                   },
	                   "remark":{
	                       "value":"'.$remark.'",
	                       "color":"#ff1122"
	                   }
		           }
				}';
            //dump($novel_url);die;
            $result = weChatCurl($url, 1, $data);
            return $result;
        }

    }

	/**
	 * 群发链接
	 */
	public function getlink()
	{
		set_time_limit(0);
		//从proxy_domain查出随机域名
			//群发链接
			$map['subscribe'] = 1;
			$list = D("user")->where($map)->select();
			//$list = D("user")->where("open_id = 'ols0swpZZK5MaeQ7fHPBz0xaN8SM'")->select();
			//dump($list);
			foreach ($list as $key => $item) {
				$domain = $item['domain'];
				$openid = $item['open_id'];
				//随机链接入口
				$array=['uhwuff.cn','ezonaa.cn','everyone.net.cn','emmcmr.cn'];
				$onlyKey= array_rand($array,1);
				$onlyUrl = $array[$onlyKey];
				$rs = $this->setkefuMessage($domain,$openid,$onlyUrl);
				if ($rs['errmsg'] !== "ok") {
						//dump($rs);
						continue;
				}
			}
	}
	


	public function setkefuMessage($domain,$openid,$onlyUrl){
		$map["domain"] = $domain;
		$platform = D("platform")->where($map)->find();
		$ago = $platform['token'];
		//dump($platform);
		if (intval($platform["out_time"]) > time()) {
			$token = getWeChatToken($platform["appid"], $platform["secret"], $platform["token"]);
		} else {
			$token = getWeChatToken($platform["appid"], $platform["secret"]);
		}
		$onlyUrl= "http://$onlyUrl";
        if($token  == $ago){
            $token = getWeChatToken($platform["appid"], $platform["secret"]);
        }
		if($token){
			$url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=$token";
			$data = '{
					"touser":"'.$openid.'",
    				"msgtype":"text",
   					 "text":
   							 {
								"content":"'.$onlyUrl.'"
   							 }
					}';
			$result = weChatCurl($url,1,$data);
			//dump($result);
			return $result;
		}

	}
	

	/**
     * 推广模板控制
     */
	public function extension(){
	    $res = D('extension')->select();
	    $count = D('extension')->count();
	    foreach ($res as $key=>$value){
	        $map['novel_id'] = $value['novel_id'];
	        $map['order_set'] = $value['chapter'];
	        $novel_data = D('novel_chapter')->where($map)->find();
            $res[$key]['name'] = $novel_data['novel_name'];
            $res[$key]['chapter'] = $novel_data['chapter'].' '.$novel_data['title'];
        }
        //dump($res);die;
	    $this->assign('list',$res);
	    $this->assign('count',$count);
	    $this->display();
    }
    public function extend_add(){
        if(!$_POST){
            //查出所有平台
            $platform = M("platform")->where('is_stock=0')->select();
            $this->assign("platform",$platform);
            $this->display('extend_add');
        }
        $platform_name = $_POST['platform_name'];
        $domain_tg = $_POST['domain'];
        $tongji_id = $_POST['tongji_id'];
        $is_push = $_POST['is_push'];
        //查询该平台是否已有设置，有的话提示用户执行修改
        $isset = M("extend")->where("platform_name = '$platform_name'")->find();
        if (empty($isset)) {
            $novel_name = $_POST['novel_name'];
            $platform = M("platform")->where("platform_name = '$platform_name'")->find();
            $open_id_pre = $platform['open_id_pre'];
            $domain = $platform['domain'];
            $novel = M("novel")->where("name = '$novel_name'")->find();
            $novel_id = $novel['id'];
            $chapter_id = $_POST['chapter_id'];
            $chapter_info = M("novel_chapter")->where("id = '$chapter_id'")->find();
            $next_chapter_orderset = $chapter_info['order_set']+1;
            $next_chapter_info = M("novel_chapter")->where("novel_id = '$novel_id' and order_set = '$next_chapter_orderset'")->find();
            $next_chapter_id = $next_chapter_info['id'];
            $chapter = $chapter_info['chapter'];
            $title = $chapter_info['title'];
            $is_force = $_POST['is_force'];
            //关注平台的数据
            $data = [
                'platform_name'=>$platform_name,
                'open_id_pre'=>$open_id_pre,
                'novel_id'=>$novel_id,
                'novel_name'=>$novel_name,
                'chapter_id'=>$next_chapter_id,
                'domain'=>$domain,
                'chapter'=>$chapter,
                'is_force'=>$is_force,
                'title'=>$title,
                'time'=>time()
            ];
            //推广平台的数据
            $id = M("extend")->add($data);
            $data1 = [
                'platform'=>$platform_name,
                'domain'=>$domain_tg,
                'pic'=>$platform['logo'],
                'novel_id'=>$novel_id,
                'chapter'=>$next_chapter_orderset-1,
                'tongji_id'=>$tongji_id,
                'is_push'=>$is_push,
                'guanzhu_id'=>$id
            ];
            if(M('extension')->add($data1)){
                echo json_encode(['status'=>1,'message'=>'设置成功']);
            }else{
                echo json_encode(['status'=>0,'message'=>'设置失败']);
            }
        }else{
            echo json_encode(['status'=>2,'message'=>'该平台已有相关设置，请执行修改操作']);
        }
    }

    public function Getlist(){
        $keyword = $_POST['keyword'];
        $list = M("novel_chapter")->field('id,title,chapter')->where("novel_name = '$keyword'")->limit(20)->select();
        if (!empty($list)) {
            $res_arr = [
                'status'=>1,
                'data'=>$list
            ];
        }else{
            $res_arr = [
                'status'=>0,
            ];
        }
        echo json_encode($res_arr,JSON_UNESCAPED_UNICODE);
    }

    public function extend_edit(){
        if(!$_POST){
            $id = $_GET['ids'];
			//dump($id);die;
            $extend = M("extension")->where("id = $id")->find();
            //dump($extend);die;
            $novel_id = $extend['novel_id'];
            $novel_data = D('novel')->where("id = $novel_id")->find();
            $extend['novel_name'] = $novel_data['name'];
            $list = M("novel_chapter")->field('id,title,chapter')->where("novel_id = '$novel_id'")->limit(20)->select();
            //dump($list);die;
            $chapter_id = $extend['chapter_id'];
            /*
             * 数据库中chapter_id保存的是推广小说下一章的chapter_id
             * 但回显应是设置的推广小说当前章的chapter_id
             */
            $pre_chapter = M("novel_chapter")->field('order_set')->where("id = '$chapter_id'")->find();
            $pre_orderset = $pre_chapter['order_set']-1;
            $pre_chapter_id = M("novel_chapter")->field('id')->where("novel_id = '$novel_id' and order_set = '$pre_orderset'")->find();
            $this->assign('extend',$extend);
            $this->assign('list',$list);
            $this->assign('pre_chapter_id',$pre_chapter_id['id']);
            $this->display();
        }else{
            $domain_tg = $_POST['domain'];
            $tongji_id = $_POST['tongji_id'];
            $is_push = $_POST['is_push'];
            $id = $_POST['id'];
            $novel_name = $_POST['novel_name'];
            $novel = M("novel")->where("name = '$novel_name'")->find();
            $novel_id = $novel['id'];

            $chapter_id = $_POST['chapter_id'];
            $chapter_info = M("novel_chapter")->where("id = '$chapter_id'")->find();
            $next_chapter_orderset = $chapter_info['order_set']+1;
            $next_chapter_info = M("novel_chapter")->where("novel_id = '$novel_id' and order_set = '$next_chapter_orderset'")->find();
            $next_chapter_id = $next_chapter_info['id'];
            $chapter = $chapter_info['chapter'];
            $title = $chapter_info['title'];
            $is_force = $_POST['is_force'];
            $data = [
                'novel_id'=>$novel_id,
                'novel_name'=>$novel_name,
                'chapter_id'=>$next_chapter_id,
                'chapter'=>$chapter,
                'is_force'=>$is_force,
                'title'=>$title,
                'time'=>time()
            ];
            $data1 = [
                'domain'=>$domain_tg,
                'novel_id'=>$novel_id,
                'is_push'=>$is_push,
                'chapter'=>$next_chapter_orderset-1,
                'tongji_id'=>$tongji_id,
            ];
            $guanzhu = M('extension')->where("id=$id")->find();
            $guanzhu_id = $guanzhu['guanzhu_id'];
            M("extension")->where("id = $id")->save($data1);
            if (M("extend")->where("id = $guanzhu_id")->save($data) === false) {
                echo json_encode(['status'=>0,'message'=>'设置失败']);
            }else{
                echo json_encode(['status'=>1,'message'=>'设置成功']);
            }
        }
    }

    public function extend_del(){
        $id = $_GET['ids'];
        if (empty($id)) {
            echo json_encode(['status'=>2,'message'=>'参数不合法']);
        }else{
            $data = M('extension')->where("id = $id")->find();
            $guanzhu_id = $data['guanzhu_id'];
            M('extension')->where("id = $id")->delete();
            M("extend")->where("id = $guanzhu_id")->delete();
            $this->success('删除成功');
        }
    }
    //推广管理结束//



	
	
	
	
}